﻿/* 2020.9.2 增加2018分支（关于ReportResult)
 * 
 */
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using System.IO;
using UnityEngine;
#if UNITY_2018_1_OR_NEWER
using UnityEditor.Build.Reporting;
#endif

/// <summary>
/// 打包.bat用
/// </summary>
public class SBuildTool
{
    public const string kPreSTool = "SBuildTool/";
    const string kPrepareAndroid    = kPreSTool+"(1) PrepareAndroid";
    const string kBuildAB           = kPreSTool + "(2) BuildAssetBundle(Basic & All NPC)";
    const string kExportProject     = kPreSTool + "(3) ExportProject";
    //[MenuItem(kPrepareAndroid, false, 1101)]
    public static void PrepareAndroid()
    {
        BuildTargetGroup targetGroup = BuildTargetGroup.Android;
        if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android)
        {
            EditorUserBuildSettings.SwitchActiveBuildTarget(targetGroup, BuildTarget.Android);
        }
        string ori = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
        //Logger.Log("old DefineSymbols: " + ori);
        List<string> defineSymbols = new List<string>(ori.Split(';'));

        List<string> addSymbols = new List<string>() { "CLIENT_ON" };
        List<string> removeSymbols = new List<string>();// { "CLIENT_DEBUG" };

        for (int i = 0; i < addSymbols.Count; ++i)
        {
            bool have = false;
            for (int j = 0; j < defineSymbols.Count; ++j)
            {
                if (addSymbols[i].Equals(defineSymbols[j]))
                {
                    have = true;
                    break;
                }
            }

            if (!have)
            {
                defineSymbols.Add(addSymbols[i]);
            }
        }

        for (int i = 0; i < removeSymbols.Count; ++i)
        {
            defineSymbols.RemoveAll(s => (s.Equals(removeSymbols[i])));
        }

        string newSymbols = string.Join(";", defineSymbols.ToArray());
        //Logger.Log("new DefineSymbols: " + newSymbols);

        PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, newSymbols);
    }

    //[MenuItem(kBuildAB, false, 1102)]
    public static void BuildAB()
    {
       // AssetBundles.AssetBundleMenuItems.BuildBasicABAndCopyToStreamingAssets();
    }

    public static void BuildProject()
    {
        bool isAndroid = EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android;
        bool isIOS = EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS;
        string projPath;

        if (isAndroid)
        {
            projPath = System.Environment.CurrentDirectory + "/OutPut/ExportAndroidProject.apk";
            //GameUtility.SafeDeleteDir(projPath);
            string info = "";
#if UNITY_2018_1_OR_NEWER
            var report = BuildPipeline.BuildPlayer(GetBuildScenes(), projPath,
                BuildTarget.Android, BuildOptions.Development);
            if (report.summary.result != BuildResult.Succeeded)
            {
                info = "错误个数：" + report.summary.totalErrors;
            }
#else
            info = BuildPipeline.BuildPlayer(GetBuildScenes(), projPath,
                BuildTarget.Android, BuildOptions.Development);
#endif
        }
        else if(isIOS)
        { }
    }
    [MenuItem(kExportProject, false, 1103)]
    public static void ExportProject()
    {
        //TODO:做一些检查吧
        if (BuildCheck() == false) return;

        bool isAndroid = EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android;
        bool isIOS = EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS;
        string projPath;

        if (isAndroid)
        {
            projPath = System.Environment.CurrentDirectory + "/OutPut/ExportAndroidProject.apk";
            //GameUtility.SafeDeleteDir(projPath);
            SaveCreateFolder(projPath);
            string info = "";
            //TODO:2018版本后，貌似目前不能在gradle模式下执行
            if (EditorUserBuildSettings.androidBuildSystem == AndroidBuildSystem.Gradle)
            {
                if (EditorUtility.DisplayDialog("", "Gradle打包模式，好像无法输出.apk，要继续吗？", "继续", "取消") == false)
                {
                    return;
                }
            }
#if UNITY_2018_1_OR_NEWER
            var report = BuildPipeline.BuildPlayer(GetBuildScenes(), projPath,
                BuildTarget.Android, BuildOptions.AcceptExternalModificationsToPlayer);
            if (report.summary.result != BuildResult.Succeeded)
            {
                info = "错误个数：" + report.summary.totalErrors;
            }
#else
            info = BuildPipeline.BuildPlayer(GetBuildScenes(), projPath,
                BuildTarget.Android, BuildOptions.AcceptExternalModificationsToPlayer);
#endif

            if (!string.IsNullOrEmpty(info))
            {
                Debug.LogError(info);
            }
        }
        else if (isIOS)
        {
            projPath = System.Environment.CurrentDirectory + "/OutPut/UnityProj";
            // GameUtility.SafeDeleteDir(projPath);
            SaveCreateFolder(projPath);
            string info = "";
#if UNITY_2018_1_OR_NEWER
            var report = BuildPipeline.BuildPlayer(GetBuildScenes(), projPath,
                BuildTarget.iOS, BuildOptions.AcceptExternalModificationsToPlayer);
            if (report.summary.result != BuildResult.Succeeded)
            {
                info = "错误个数：" + report.summary.totalErrors;
            }
#else
            info  = BuildPipeline.BuildPlayer(GetBuildScenes(), projPath,
                BuildTarget.iOS, BuildOptions.AcceptExternalModificationsToPlayer);
#endif
            if (!string.IsNullOrEmpty(info))
            {
                Debug.LogError(info);
            }
        }
        else
        {
            Debug.LogError("暂时只支持手机平台");
        }
    }

    static string[] GetBuildScenes()
    {
        List<string> names = new List<string>();
        foreach (EditorBuildSettingsScene e in EditorBuildSettings.scenes)
        {
            if (e != null && e.enabled)
            {
                names.Add(e.path);
            }
        }
        return names.ToArray();
    }
    /// <summary>
    /// 打包前，切换ios平台的方法，从android逻辑搬过来，无调试需求，也就无公布MenuItem
    /// </summary>
    public static void PrepareIOS()
    {
        BuildTargetGroup targetGroup = BuildTargetGroup.iOS;
        if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.iOS)
        {
            EditorUserBuildSettings.SwitchActiveBuildTarget(targetGroup, BuildTarget.iOS);
        }
        string ori = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
       // Logger.Log("old DefineSymbols: " + ori);
        List<string> defineSymbols = new List<string>(ori.Split(';'));
        //TODO:提取这个标签处理代码，android和ios可通用
        List<string> addSymbols = new List<string>() { "CLIENT_ON" };
        List<string> removeSymbols = new List<string>();// { "CLIENT_DEBUG" };

        for (int i = 0; i < addSymbols.Count; ++i)
        {
            bool have = false;
            for (int j = 0; j < defineSymbols.Count; ++j)
            {
                if (addSymbols[i].Equals(defineSymbols[j]))
                {
                    have = true;
                    break;
                }
            }

            if (!have)
            {
                defineSymbols.Add(addSymbols[i]);
            }
        }

        for (int i = 0; i < removeSymbols.Count; ++i)
        {
            defineSymbols.RemoveAll(s => (s.Equals(removeSymbols[i])));
        }

        string newSymbols = string.Join(";", defineSymbols.ToArray());
       // Logger.Log("new DefineSymbols: " + newSymbols);

        PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, newSymbols);
    }
    /// <summary>
    /// 判断目录不存在，则创建；不会删除，可放心用
    /// </summary>
    /// <param name="path">可用相对路径</param>
    static void SaveCreateFolder(string path)
    {
        string dir = Path.GetDirectoryName(path);
        //unity 自带相对路径
        if(Directory.Exists(dir)==false)
            {
            Directory.CreateDirectory(dir);
        }
               
    }

    static bool BuildCheck()
    {
        bool isError = false;
        string err = "";
        if (EditorBuildSettings.scenes == null || EditorBuildSettings.scenes.Length == 0)
        {
            err = "无法打包：缺少场景，请先在Build Setting添加";
            Debug.LogWarning(err);
            EditorUtility.DisplayDialog("", err, "了解");
            isError = true;
        }

        return !isError;
    }
}

